import mqtt from 'mqtt';

let client;

let callbackMapping = {};

//创建一个客户端对象
/* 连接服务器 */
function connectMQTT(){
    const host = "ws://localhost";			//服务器地址
    const port = "8083";			//服务器端口
    const path = "/mqtt";			//服务器路径
    const clientID = randomID();	//clientID 随机生成
    const url = host+':'+port+path;								//URL地址
    console.log(url);											//后台输入URL地址
    const options = {												//创建一个参数对象
        clientId:clientID,										//clientID
    };
    client = mqtt.connect(url, options);							//连接服务器
    client.stream.on('error', function(err) {					//连接错误时触发
        console.error('Connection error:'+err);
        console.log('连接失败');
        client.end();											//关闭客户端对象
    })
    //连接服务器后触发
    client.on('connect',function(packet){
        console.log("mqtt服务器已连接");
    })
    // 收到消息触发
    client.on('message', messageHandler);
}

function getMQTTConnect() {
    if (client) {
        return client;
    }
    connectMQTT();
    return client;
}

/* 断开连接服务器 */
function connectEND(){
    if(client && client.connected){
        client.end();
        console.log("已断开连接");
        document.getElementById("connectBtn").removeAttribute("disabled","disabled");		//连接按钮设为可用
        document.getElementById("connectBtn").innerHTML = "连接";							//连接按钮显示为连接
        document.getElementById("disconnectBtn").setAttribute("disabled","disabled");		//断开按钮设为不可用
        document.getElementById("disconnectBtn").innerHTML = "已断开";						//断开按钮显示已断开
        var messageTextArea = document.getElementById("messageTextArea");					//textarea添加文本
        messageTextArea.value += "已断开\n"													//textarea添加文本
    }else{
        console.log("未连接");
    }
}

/* 发送消息 */
function sendMessage() {
    var topic = document.getElementById("topic").value;			//获取主题
    var message = document.getElementById("message").value;		//获取消息文本
    if(client && client.connected){
        client.publish(topic, message);							//发送消息
        console.log("已发送");
    }else{
        console.log("未连接");
    }
}

/* 订阅主题 */
function subscribeTopic(topic, callback){
    client.subscribe(topic);											//定阅主题
    console.log("已订阅:"+topic);
    callbackMapping[topic] = callback;
}


/* 接收消息函数 */
function messageHandler(topic,message){
    const str = message.toString();//监听消息函数
    console.log("收到来自主题:"+topic+"的消息:"+str);

    if (callbackMapping[topic]) {
        callbackMapping[topic](str);
    }
}

/* 生成随机clientID */
function randomID(){
    return 'clientID_' + Math.random().toString(16).substring(2, 8)
}

export default {
    getMQTTConnect: getMQTTConnect,
    subscribeTopic: subscribeTopic
};
